import { inject } from 'vue';

export default (ujt: any) => {
    const { $fn, $model, $db, $dbwork, $global } = ujt;
    function initAppModel(model: any = 'testkdd') {
        const $vueProxy: any = inject('$vueProxy');
        $vueProxy?.$installplugs(model);
        if ($vueProxy?.['$engine' + model]) {
            Object.assign($fn, $vueProxy['$engine' + model]);
            if ($vueProxy?.['$engineuse' + model]) {
                Object.assign($fn, $vueProxy['$engineuse' + model]);
            }
        }
        if (!$model[model]) {
            $model[model] = {};
        }
        if (!$dbwork[model]) {
            $dbwork[model] = {};
        }
        if (!$db[model]) {
            $db[model] = {};
        }
        // 保存用户配置
        $fn.setconfig = (userfile: string, data: any) => {
            return $fn.api['webserver'].apiPost(
                '/api/asaijson/manage/update/?path=./webclient/webmodel/sys/setting/' +
                    userfile +
                    '.json',
                data
            );
        };
        // 模块内的语言切换
        $fn.changelangpro = (langty: string = '') => {
            return $fn
                .changelang($global.config.langcur || langty)
                .then((res: string) => {
                    if ($global?.sys?.local?.lang) {
                        if (model && $fn.ws?.[model]) {
                            // 和后端语言保持一致
                            $fn.ws[model].wsSend({
                                id: '1',
                                ty: 'common/setlanguage',
                                db: res,
                            });
                        }
                    } else {
                        $fn.setconfig('settinglang', {
                            lang: langty,
                        });
                    }
                });
        };
        // 风格切换
        $fn.changethemepro = (themety: string = '') => {
            if ($global?.sys?.local?.theme) {
                return $fn.changetheme(themety);
            } else {
                return $fn.setconfig('settingtheme', {
                    theme: themety,
                });
            }
        };
        const apppro: any = [$fn.initlang($global.config.langcur || '')];
        apppro.push(
            $fn.initmodel(model + '/dirmodel.json').then((res: any) => {
                if (res) {
                    Object.assign($model[model], res);
                }
            })
        );
        return Promise.all(apppro);
    }

    return { initAppModel };
};
